package com.luo.beanfacotryprocesser;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;

import java.util.Calendar;

/**
 * 通过bean工厂后置处理器我们还可以在初始化时进行一些额外的操作
 * 这个作为bean工厂后置处理器，会比普通bean先实例化并放在一个列表里面(beanFactoryPostProcessors)
 */
public class BeanModifier implements BeanFactoryPostProcessor, BeanDefinitionRegistryPostProcessor {
	public BeanModifier() {
		System.out.println("BeanModifier");
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		System.out.println("BeanModifier#postProcessBeanFactory");
		try {
			Calendar calendar = Calendar.getInstance();
			if (calendar.get(Calendar.AM_PM) == Calendar.PM) {
				//这时候welcomer还没实例化，只是告诉BeanDefinition他的属性是这个值
				BeanDefinition welcomerDef = beanFactory.getBeanDefinition("welcomerBean");
				welcomerDef.getPropertyValues().add("welcomeText", "Good afternoon");
			}

		} catch (Exception e) {
			System.out.println("An error occurred on setting welcomeText");
		}
	}

	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		System.out.println("BeanModifier#postProcessBeanDefinitionRegistry");
	}
}